package main;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import framework.system.FrontEnd;


public class Client {
	private static FrontEnd frontEnd;

	public static void main(String[] args) {
		String host = "localhost";
		String port = Integer.toString(Registry.REGISTRY_PORT);
		try {
			Registry registry = LocateRegistry.getRegistry(host, Registry.REGISTRY_PORT);
			frontEnd = (FrontEnd) registry.lookup(
					"rmi://" + host + ":" + port + "/" + FrontEnd.SERVICENAME);

			String welcome = "" +
				"Welcome to the Client UI!" + "\n" +
				"_________________________" + "\n" +
				"Commands:" + "\n" +
				"\t" + "put <K> <V>" + "\n" +
				"\t" + "get <K>" + "\n" +
				"\t" + "remove <K>" + "\n";
			System.out.println(welcome);
			
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String line;
			while (! (line=in.readLine()).equalsIgnoreCase("exit") ){
				handleRequest(line.split(" "));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void handleRequest(String[] args) throws Exception {
		String command = args[0];
		if (command.equals("put")){
			frontEnd.put(args[1], args[2]);
		} else if (command.equals("get")) {
			String[] list = frontEnd.get(args[1]);
			if (list!=null) {
				for (int i=0; i<list.length; i++) {
					System.out.println("\t["+i+"]: "+list[i]);
				}
			} else {
				System.out.println("\tNo value");
			}
		} else if (command.equals("remove")) {
			String[] list = frontEnd.remove(args[1]);
			if (list!=null) {
				for (int i=0; i<list.length; i++) {
					System.out.println("\t["+i+"]: "+list[i]);
				}
			} else {
				System.out.println("\tNo value");
			}
		}
	}

}
